package com.formiaomiao.demain.activity;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.formiaomiao.demain.R;
import com.formiaomiao.demain.base.BaseActivity;
import com.formiaomiao.demain.base.BaseApplication;
import com.formiaomiao.demain.base.BaseUrl;
import com.formiaomiao.demain.db.MsgBean;
import com.formiaomiao.demain.greendao.IsPushBeanDao;
import com.formiaomiao.demain.greendao.MsgBeanDao;
import com.formiaomiao.demain.util.Constants;
import com.formiaomiao.demain.util.MessageEvent;
import com.formiaomiao.demain.util.PreferenceUtils;
import com.formiaomiao.demain.util.PreferenceValues;
import com.formiaomiao.demain.util.StaticValues;
import com.formiaomiao.demain.util.ToastUtils;
import com.formiaomiao.demain.util.UseGlideUtils;
import com.formiaomiao.demain.weight.LoadingDialog;
import com.hyphenate.chat.EMClient;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FriendDetailActivity extends BaseActivity {

    @BindView(R.id.iv_class_back)
    ImageView ivClassBack;
    @BindView(R.id.tv_class_name)
    TextView tvClassName;
    @BindView(R.id.tv_class_submit)
    TextView tvClassSubmit;
    @BindView(R.id.iv_friend_head)
    ImageView ivFriendHead;
    @BindView(R.id.tv_friend_name)
    TextView tvFriendName;
    @BindView(R.id.tv_friend_phone)
    TextView tvFriendPhone;
    @BindView(R.id.tv_friend_chat)
    TextView tvFriendChat;
    @BindView(R.id.tv_friend_delete)
    TextView tvFriendDelete;
    @BindView(R.id.tv_friend_remarks)
    TextView tvFriendRemarks;

    private static FriendDetailActivity friendDetailActivity;

    LoadingDialog loadingDialog;

    MsgBeanDao msgBeanDao;

    public static FriendDetailActivity getInstances() {
        return friendDetailActivity;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_friend_detail);
        ButterKnife.bind(this);
        ViewInit();
    }

    @SuppressLint("SetTextI18n")
    private void ViewInit() {
        friendDetailActivity = this;
        tvClassName.setText("用户详情");
        msgBeanDao = BaseApplication.getInstances().getDaoSession().getMsgBeanDao();
        loadingDialog = new LoadingDialog(this);
        UseGlideUtils.setGlide(this, getIntent().getStringExtra("userhead"), ivFriendHead);
        tvFriendName.setText("昵称: " + (getIntent().getStringExtra("friendremarks") == null ?
                getIntent().getStringExtra("nickname") : getIntent().getStringExtra("friendremarks")));
        tvFriendPhone.setText("手机号: " + getIntent().getStringExtra("username")
                .substring(0, 2) + "****" + getIntent().getStringExtra("username")
                .substring(6, getIntent().getStringExtra("username").length() - 1));
        if (getIntent().getIntExtra("type", 0) == Constants.CHAT_ITEM_TYPE_RIGHT) {
            tvFriendDelete.setVisibility(View.GONE);
        }
    }

    /**
     * 删除好友
     */
    private void DeleteFriendInit() {
        HttpParams params = new HttpParams();
        params.put("friendfrom", StaticValues.userid);
        params.put("friendto", getIntent().getIntExtra("id", 0));
        OkGo.<String>post(BaseUrl.DELETEFRIEND)
                .headers("Authorization", PreferenceUtils.getString(this, PreferenceValues.TOKEN))
                .params(params).tag(this).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                if (response.body().contains("成功")) {
                    ToastUtils.show(FriendDetailActivity.this, "删除成功");
                    //删除和某个user会话，如果需要保留聊天记录，传false
                    EMClient.getInstance().chatManager().deleteConversation(getIntent().getStringExtra("username"), true);
                    List<MsgBean> msgBeans = msgBeanDao.loadAll();
                    for (int j = 0; j < msgBeans.size(); j++) {
                        if (msgBeans.get(j).getChatMsgId().equals(StaticValues.username + "#" + getIntent().getStringExtra("username"))) {
                            msgBeanDao.deleteByKey(msgBeans.get(j).getId());
                        }
                    }
                    finish();
                    if (ChatSettingsActivity.getInstances() != null) {
                        ChatSettingsActivity.getInstances().finish();
                    }
                    if (ChatActivity.getInstance() != null) {
                        ChatActivity.getInstance().finish();
                    }
                } else {
                    ToastUtils.show(FriendDetailActivity.this, "删除失败");
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void DleteEventBus(MessageEvent messages) {
        if (!messages.getMessage().contains("删除聊天记录")||
                !messages.getMessage().equals("修改背景")) {
            tvFriendName.setText(messages.getMessage());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.iv_class_back, R.id.tv_friend_chat, R.id.tv_friend_delete, R.id.tv_friend_remarks})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.iv_class_back:
                finish();
                break;
            case R.id.tv_friend_remarks:
                intent.setClass(this, UpdateFriendsRemarksActivity.class);
                intent.putExtra("id", getIntent().getIntExtra("id", 0));
                intent.putExtra("username", getIntent().getStringExtra("username"));
                intent.putExtra("friendremarks", getIntent().getStringExtra("friendremarks")==null ?
                        "" : getIntent().getStringExtra("friendremarks"));
                startActivity(intent);
                break;
            case R.id.tv_friend_chat:
                intent.setClass(this, DemainUserActivity.class);
                intent.putExtra("id", getIntent().getIntExtra("id", 0));
                intent.putExtra("name", getIntent().getStringExtra("nickname"));
                intent.putExtra("head", getIntent().getStringExtra("userhead"));
                intent.putExtra("username", getIntent().getStringExtra("username"));
                intent.putExtra("friendremarks", getIntent().getStringExtra("friendremarks") == null ||
                        getIntent().getStringExtra("friendremarks").equals("") ?
                        getIntent().getStringExtra("nickname") :
                        getIntent().getStringExtra("friendremarks"));
                startActivity(intent);
                break;
            case R.id.tv_friend_delete:
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                dialog.setMessage("是否删除好友");
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        DeleteFriendInit();
                    }
                });
                dialog.show();
                break;
        }
    }

}
